#include "LogMgr.h"
#include <stdarg.h>
#include <iostream>
#include <time.h>
#include "Config.h"

#ifdef WIN32
#include<direct.h> 
#else
#include <sys/types.h>
#include <sys/stat.h>
#endif

CLogMgr::CLogMgr()
	:bInit(false)
{
}


CLogMgr::~CLogMgr()
{
	if (file.is_open())
		file.close();
}

CLogMgr * CLogMgr::Instance()
{
	static CLogMgr _mgr;
	return &_mgr;
}

bool CLogMgr::InitLog()
{
	if (file.is_open())
		file.close();

	curDate = Date::getCurrentDate();
	char szPath[256],szFileName[256];
#ifdef WIN32
	sprintf(szPath, "%slogs", CConfig::GetAppPath().c_str());
	sprintf(szFileName, "%slogs\\%04d_%02d_%02d.log", CConfig::GetAppPath().c_str()
		, curDate.Year(), curDate.Month(), curDate.Day());
#else
	sprintf(szPath, "%slogs", CConfig::GetAppPath().c_str());
	sprintf(szFileName, "%slogs/%04d_%02d_%02d.log", CConfig::GetAppPath().c_str()
		, curDate.Year(), curDate.Month(), curDate.Day());
#endif

#ifdef WIN32
	_mkdir(szPath);
#else
	mkdir(szPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif
	file.open(szFileName, std::ios_base::out|std::ios_base::app);

	if (!file.is_open())
		return false;

	return true;
}

void CLogMgr::WriteLog(const char * format, ...)
{
	if (!bInit || Date::getCurrentDate() != curDate)
	{
		if (!(bInit=InitLog()))
		{
			std::cout << "Init log file failed!" << std::endl;
			return ;
		}
	}
	if (bInit)
	{
		char strMsg[256];
		va_list ap;
		va_start(ap, format);
		vsprintf(strMsg, format, ap);
		va_end(ap);

		time_t now;
		struct tm *tm_now;
		time(&now);
		tm_now = localtime(&now);

		char szShow[1024];

		sprintf(szShow,"%04d-%02d-%02d %02d:%02d:%02d %s"
			, tm_now->tm_year + 1900, tm_now->tm_mon + 1, tm_now->tm_mday
			, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec, strMsg);
		std::cout << szShow<<std::endl;
		file << szShow<<std::endl;
	}

}
